package cn.coisini.utils;

import cn.coisini.model.common.dtos.Result;
import cn.coisini.model.common.enums.ResultEnum;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author xiangshaw
 * Description: 异常处理工具类
 */
@Log4j2
public class ExceptionUtil {

    private static final String CONTENT_TYPE = MediaType.APPLICATION_JSON_VALUE;
    private static final String CHARSET = StandardCharsets.UTF_8.name();

    /**
     * 处理异常
     * @param response 响应对象
     * @param resultEnum 响应状态码枚举
     */
    public static void handleException(HttpServletResponse response, ResultEnum resultEnum) {
        // 根据响应状态码枚举设置HTTP状态码
        int status = switch (resultEnum){
            case REQUIRES_LOGIN, NO_OPERATOR_AUTH, TOKEN_EXPIRED, TOKEN_INVALID, TOKEN_EXCEPTION -> HttpStatus.UNAUTHORIZED.value();
            case NEED_ADMIND -> HttpStatus.FORBIDDEN.value();
            default -> HttpStatus.INTERNAL_SERVER_ERROR.value();
        };
        // 设置响应状态码
        response.setStatus(status);
        // 设置响应类型为 JSON
        response.setContentType(CONTENT_TYPE);
        // 设置字符编码
        response.setCharacterEncoding(CHARSET);
        // 构建错误详情
        String jsonErrorDetails = JSONUtil.toJsonStr(Result.error(resultEnum));
        try(PrintWriter printWriter = response.getWriter()){
            printWriter.write(jsonErrorDetails);
        } catch (IOException e) {
            log.error("写入JSON响应时出错:", e);
        }
    }
}
